/**
 * 
 */
package com.huawei.esdk.uc.sametime.services;

import java.util.Map;

import org.apache.log4j.Logger;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.widgets.Display;

import com.huawei.esdk.uc.jna.Constants;
import com.huawei.esdk.uc.jna.UCService;
import com.huawei.esdk.uc.jna.util.StringUtil;
import com.huawei.esdk.uc.sametime.ConstantsDefines;
import com.huawei.esdk.uc.sametime.EsdkPluginActivator;
import com.huawei.esdk.uc.sametime.international.Messages;
import com.huawei.esdk.uc.sametime.preferences.PreferenceConstants;
import com.huawei.esdk.uc.sametime.uccallbackimpl.UCLoginCallBackImpl;
import com.huawei.esdk.uc.sametime.uccallbackimpl.UCStatusChangedCallBackImpl;
import com.huawei.esdk.uc.sametime.util.GlobalConfiguration;
import com.huawei.esdk.uc.sametime.util.PluginUtil;

/**
 * @author y00175154
 * 
 */
public class UCLoginService
{

    private static Logger logger = Logger.getLogger(UCLoginService.class);

    public static void startLoginUC()
    {
        logger.info("load binding uc accountinfo");

        if (!PluginUtil.isUCConfig())
        {
            logger.error("UC config error");
            Display.getDefault().syncExec(new Runnable()
            {
                @Override
                public void run()
                {
                    MessageDialog
                            .openWarning(
                                    Display.getDefault().getActiveShell(),
                                    Messages.TIPS,
                                    Messages.SametimeCommunitylistener_UC_CONFIG_NOT_PROPER);
                }
            });
            GlobalConfiguration.getInstance().setUCLogin(false);
            return;
        }
//        if(!GlobalConfiguration.getInstance().isUCInit())
//        {
//            initSDK();
//        }

        IPreferenceStore preferenceStore = EsdkPluginActivator.getDefault()
                .getPreferenceStore();
        String userName = preferenceStore
                .getString(PreferenceConstants.P_USERNAME);
        String password = preferenceStore
                .getString(PreferenceConstants.P_PASSWORD);
        String ucSvrIp = preferenceStore
                .getString(PreferenceConstants.P_UCSVRIP);
        int port = preferenceStore.getInt(PreferenceConstants.P_PORT);

        logger.info("preferenceStore UC info:" + userName + ", and ucSvrIp:"
                + ucSvrIp + ", and port:" + port);

        if (!StringUtil.isEmptyStr(userName)
                && !StringUtil.isEmptyStr(password)
                && !StringUtil.isEmptyStr(ucSvrIp))
        {
            boolean loginRes = UCLoginService.loginUC(userName, password,
                    ucSvrIp, port);
            if (!loginRes)
            {
                logger.error("login request send failed");
            }
            else
            {
                logger.debug("login request send success");
            }
        }

    }

    public static void startLogoutUC()
    {
        logger.debug("start Logout UC");
        // 插件登出UC服务
        boolean logoutRes = UCLoginService.logoutUC();
        if (!logoutRes)
        {
            logger.error("UC Logout error!");
        }
        // unInitSDK();
    }

    public static void initSDK()
    {
        logger.debug("ucsdk init");
        int iRet = UCService.getInstance().UC_SDK_Init();
        logger.debug("ucsdk init, retcode is: " + iRet);

        if (Constants.UCServiceRetvCode.UC_SDK_Success == iRet)
        {
            GlobalConfiguration.getInstance().setUCInit(true);
//            UCService.getInstance().UC_SDK_SetStatusChangedCB(
//                    UCStatusChangedCallBackImpl.getInstance());
        }
        else
        {
            GlobalConfiguration.getInstance().setUCInit(false);
            logger.error("ucsdk init fail");
        }
    }

    public static int unInitSDK()
    {
        logger.debug("ucsdk uninit");
        int iRet = UCService.getInstance().UC_SDK_UnInit();
        logger.debug("ucsdk uninit end, retcode is : " + iRet);
        if (Constants.UCServiceRetvCode.UC_SDK_Success != iRet)
        {
            logger.error("ucsdk uninit fail");
        }
        else
        {
            GlobalConfiguration.getInstance().setUCInit(false);
        }
        return iRet;
    }

    private static boolean loginUC(String userName, String password,
            String ucSvrIp, int port)
    {
        logger.debug("uc login start");
        Map<String, String> selfUCAccountInfo = GlobalConfiguration
                .getInstance().getSelfUCAccountInfo();
        selfUCAccountInfo.put(ConstantsDefines.UC_CONTACT_PROPERTIES.account,
                userName);
        // 这里调用UC SDK的登录接口
        // 登录成功，返回true，登录失败，返回false
        UCService.getInstance().UC_SDK_SetLoginEventCB(
                UCLoginCallBackImpl.getInstance());
        
        UCService.getInstance().UC_SDK_SetStatusChangedCB(
                UCStatusChangedCallBackImpl.getInstance());
        
        String serverUrl = ucSvrIp + ":" + port;
        int iRet = UCService.getInstance().UC_SDK_SignInByPWD(userName,
                password, serverUrl, "2052");
        logger.debug("uc login request send result:" + iRet);
        if (0 == iRet)
        {
            return true;
        }
        return false;
    }

    private static boolean logoutUC()
    {
        logger.debug("uc logout start");
        // 这里调用UC SDK的登出接口
        // 登出成功，返回true，登录失败，返回false
        int iRet = UCService.getInstance().UC_SDK_SignOut();
        logger.debug("uc logout request send result:" + iRet);
        if (0 != iRet)
        {
            return false;
        }
        return true;
    }

}
